package com.security.control.core.social.wx.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * @author imoot@gamil.com
 * @date 2019/1/3 0003 15:04
 * -----wx相关操作实现类
 */
public class WxImpl extends AbstractOAuth2ApiBinding implements Wx {

    private Logger log = LoggerFactory.getLogger(WxImpl.class);

    private ObjectMapper objectMapper = new ObjectMapper();

    private static final String URL_GET_USER_INFO = "https://api.weixin.qq.com/sns/userinfo?openid=OPENID&lang=zh_CN";

    public WxImpl(String accessToken) {
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
    }

    @Override
    public WxUserInfo getUserInfo(String openId) {
        String url = StringUtils.replace(URL_GET_USER_INFO, "OPENID", openId);
        String result = getRestTemplate().getForObject(url, String.class);//使用SpringSocial提供的rest请求模版根据url获取用户信息
        log.info("获取用户信息：" + result);
        //判断如果返回结果中包含错误code的key，则不做处理直接返回为null
        if (StringUtils.contains(result, "errcode")) {
            return null;
        }
        try {
            WxUserInfo userInfo = objectMapper.readValue(result, WxUserInfo.class);//把请求后获得的用户信息用ObjectMapper绑定到实体类上
            return userInfo;
        } catch (Exception e) {
            log.error("获取wx用户信息出现错误：", e);
            throw new RuntimeException("获取wx用户信息出现错误" + e);
        }
    }

    //微信返回的内容编码格式为"UTF-8"，但是SpringSocial没有创建这种编码格式的请求头声明，所以需要自己实现
    @Override
    protected List<HttpMessageConverter<?>> getMessageConverters() {
        List<HttpMessageConverter<?>> messageConverters = super.getMessageConverters();
        messageConverters.remove(0);
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return messageConverters;
    }
}
